package com.jet.javatest.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * Description:
 * File: ClientSocketTest.java
 * Author: Administrator
 * Create: 2019/11/5 9:16
 */
public class ClientSocketTest {

    public static void main(String[] args) {
        try (Socket socket = new Socket("localhost", 5555)) {
            //这些顺序必须要写好,不能input和output写一起,容易引起阻塞
            OutputStream outputStream = socket.getOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);

            //输出
            String strA = "服务端你好A!\n";
            String strB = "服务端你好B!\n";
            String strC = "服务端你好C!\n";

            int allLen = (strA + strB + strC).getBytes().length;

            objectOutputStream.writeInt(allLen);
            objectOutputStream.flush();

            objectOutputStream.write(strA.getBytes());
            objectOutputStream.write(strB.getBytes());
            objectOutputStream.write(strC.getBytes());
            objectOutputStream.flush();

            InputStream inputStream = socket.getInputStream();

            ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
            //输入
            int len = objectInputStream.readInt();
            byte[] byteArray = new byte[len];
            objectInputStream.read(byteArray);
            String inputStr = new String(byteArray);
            System.out.println("ClientSocketTest inputStr = " + inputStr);


            //输出
            String strD = "服务端你好D!\n";
            String strE = "服务端你好E!\n";
            String strF = "服务端你好F!\n";

            allLen = (strD + strE + strF).getBytes().length;

            objectOutputStream.writeInt(allLen);
            objectOutputStream.flush();

            objectOutputStream.write(strD.getBytes());
            objectOutputStream.write(strE.getBytes());
            objectOutputStream.write(strF.getBytes());
            objectOutputStream.flush();
            //输入
            len = objectInputStream.readInt();
            byteArray = new byte[len];
            objectInputStream.readFully(byteArray);
            inputStr = new String(byteArray);
            System.out.println("ServerSocketTest inputStr = " + inputStr);
            inputStream.close();

        } catch (IOException e) {
            System.out.println("ClientSocketTest socket connect failed");
        }
    }

}
